package com.cwd.arm.domain.entity;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.cwd.arm.common.encoder.ArmPasswordEncoder;
import com.cwd.arm.common.exception.ArmException;
import com.cwd.arm.common.util.RandomUtil;
import lombok.Data;

import static com.cwd.arm.common.constant.SysConstant.INIT_PASSWORD;
import static com.cwd.arm.common.constant.SysConstant.SYS_ADMIN_ROLE_ID;
import static com.cwd.arm.common.constant.SysConstant.SYS_ADMIN_USER_ID;

/**
 * Created by yan on 21-11-14.
 */
@Data
public class UserEntity {

    private Long id;

    private String realName;

    private String phone;

    private String password;

    private String username;

    private String mask;

    private Long roleId;

    private boolean enabled = true;

    public boolean canDel() {
        if(isSysAdmin()){
            throw new ArmException("系统管理员不可删除");
        }
        return true;
    }

    public boolean adminVal() {
        if (isSysAdmin()) {
            if (roleId != null && SYS_ADMIN_ROLE_ID.compareTo(roleId) != 0) {
                throw new ArmException("系统管理员的角色不可修改");
            }
            if (!enabled) {
                throw new ArmException("系统管理员的用户状态不可修改");
            }
        }
        return true;
    }

    public boolean isSysAdmin() {
        return SYS_ADMIN_USER_ID.compareTo(id) == 0;
    }

    public boolean needUpdateRole() {
        if (roleId != null) {
            return true;
        }
        return false;
    }

    public boolean passwordVal() throws ArmException{
        if(password.length()<6){
            throw new ArmException("密码长度需要大于等于6位");
        }
        return true;
    }

    public void initPassword() {
        mask = RandomUtil.random(4);
        if(StringUtils.isEmpty(password)){
            password = INIT_PASSWORD;
        }
        password = ArmPasswordEncoder.getInitPassword(password,mask);
    }

}
